import axios from 'axios';
import mintUi from './mintUi';
import constant from './constant';
import router from '@/router/index';
import store from '../vuex/store';

axios.defaults.timeout = 60000;            // 响应时间
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';      // 配置请求头
axios.defaults.baseURL = constant.ajaxUrl();  // 配置接口地址
// POST传参序列化(添加请求拦截器)
axios.interceptors.request.use((config) => {
  const userToken = sessionStorage.getItem('userToken');
  if (userToken) {
    config.headers.common = {
      'Tcsl-Loongboss-Token': userToken
    };
  }
  return config;
}, (error) => {
  mintUi.openToast('传参错误');
  return Promise.reject(error);
});
// 返回状态判断(添加响应拦截器)
axios.interceptors.response.use((res) => {
  // 对响应数据做些事
  if (res.data.code === '-10006') {
    mintUi.openAlert(res.data.msg).then(result => {
      // console.log('----------------------');
      // console.log('code : -10006');
      // console.log(sessionStorage.getItem('userToken'));
      sessionStorage.removeItem('userToken');
      sessionStorage.removeItem('userInfo');
      sessionStorage.removeItem('permission');
      router.replace({
        path: '/login'
        //query: {redirect: router.currentRoute.fullPath}
      });
    });
  } else if (res.data.code !== '0') {
    mintUi.openToast(res.data.msg);
    return Promise.reject(res.data);
  }
  return res;
}, (error) => {
  mintUi.openToast('请求超时');
  return Promise.reject(error);
});
// 返回一个Promise(发送post请求)
export default {
  axiosCommon (url, params, type) {
    // console.log('----------------------');
    // console.log('发送请求');
    // console.log(url);
    // console.log(params);
    // console.log(type);
    // console.log('sessionStorage中存储的userToken');
    // console.log(sessionStorage.getItem('userToken'));
    return new Promise((resolve, reject) => {
      axios({
        method: type,
        url: url,
        data: params
      }).then(response => {
        if (response.data.code !== '-10006') {
          // console.log('response中返回的userToken');
          // console.log(response.headers['tcsl-loongboss-token']);
          store.dispatch('setToken', response.headers['tcsl-loongboss-token']);

          // **********************************************************
          // 判断是否为测试账号。为了代理商大会使用
          if (sessionStorage.getItem('userInfo')) {
            let isTestAccount = +JSON.parse(sessionStorage.getItem('userInfo') || {}).username === 13811894134;
            typeof response.data.data === 'object' && response.data.data && isTestAccount && Object.defineProperty(
              response.data.data,
              'isTest',
              {
                writable: true,
                enumerable: false,
                configurable: true,
                value: isTestAccount
              }
            );
          }
          resolve(response.data.data);
        }
      }, err => {
        reject(err);
      }).catch((error) => {
        mintUi.openToast('请求超时');
        reject(error);
      });
    });
  },

  postService (url, params) {
    return this.axiosCommon(url, params, 'post');
  },
  postWithSCode (url, params) {
    params.storeCode = store.state.shopAlter.store.storeCode ? [store.state.shopAlter.store.storeCode] : [];
    params.groupCode = store.state.shopAlter.store.groupCode;
    params.businessModelName = store.state.shopAlter.mode.modeName || '';
    params.cityCode = store.state.shopAlter.mode.cityCode || '';
    return this.axiosCommon(url, params, 'post');
  },
  getService (url) {
    return this.axiosCommon(url, '', 'get');
  },
  delService (url, params) {
    return this.axiosCommon(url, params, 'delete');
  },
  putService (url, params) {
    return this.axiosCommon(url, params, 'put');
  }
};
